package com.example.checkbox;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    Button myBtn;
    CheckBox check1,check2,check3;
    LinearLayout Linear;
    List<String> list = new ArrayList<String>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myBtn = (Button)findViewById(R.id.submitBtn);
        check1 = (CheckBox)findViewById(R.id.run);
        check2 = (CheckBox)findViewById(R.id.swim);
        check3 = (CheckBox)findViewById(R.id.badminton);
        Linear = (LinearLayout)findViewById(R.id.Linear);

        check1.setOnCheckedChangeListener((buttonView, isChecked) ->{
            if(isChecked){
                Toast.makeText(MainActivity.this,"跑步被选中",Toast.LENGTH_SHORT).show();
            }
        });
        check2.setOnCheckedChangeListener((buttonView, isChecked)->{
            if(isChecked){
                Toast.makeText(MainActivity.this,"游泳被选中",Toast.LENGTH_SHORT).show();

            }
        });

        check3.setOnCheckedChangeListener((buttonView, isChecked) ->{
            if(isChecked){
                Toast.makeText(MainActivity.this,"打羽毛球被选中",Toast.LENGTH_SHORT).show();

            }
        });

        myBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int CheckLenth = Linear.getChildCount()-1;
                for(int i=0;i<CheckLenth;i++){
                    CheckBox cb = (CheckBox)Linear.getChildAt(i);
                    if(cb.isChecked()){
                        list.add(cb.getText().toString());
                    }
                }
                if(list.isEmpty()){
                    Toast.makeText(MainActivity.this,"你什么都没选中",Toast.LENGTH_SHORT).show();

                }
                else {
                    Toast.makeText(MainActivity.this, list.toString().substring(1, list.toString().length() - 1), Toast.LENGTH_SHORT).show();
                }
                list.clear();
            }
        });
    }
}

